// pages/bookSuccess/bookSuccess.js
import { showText } from '@/utils/util'
import { getBookingInfo, getshopinfo,getBookingQrCodeImg,submitSpaBookingScore } from '../../api/spa'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUri: getApp().globalData.imgUri,
    showEvaluate: false, // 评价弹窗
    showWelfareResult: false, // 福利弹窗
    showWelfare: false, // 福利结果弹窗
    show: false,
    shopTel: '',
    info: {
      mobile: '',
      name: '赵晓晨',
      gender: 1,
      brand: '北京SKP店',
      distance: 0,
      shopAddr: '',
      qrCodeImg: '',
    },
    latitude: '',
    longitude: '',

    // 评论点赞
    starList: [
      {
        label: '门店环境',
        key:'envSocre',
        star: 0,
      },
      {
        label: '服务态度',
        key:'svcScore',
        star: 0,
      },
      {
        label: '护理效果',
        key:'effectScore',
        star: 0,
      },
    ],

    pollingInterval:null
  },
  onUnload(){
    this.stopPolling()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let t = this
    t.setData({
      params: options.params,
    })

    getBookingQrCodeImg({}).then((res) => {
      if (res.code == 200) {
        var qrCodeImg = res.data.qrCodeImg;
        t.setData({
          qrCodeImg: qrCodeImg,
        });
        t.f_getBookingInfo();
      }
    });

  },
  f_getBookingInfo(){
    let t = this;
    getBookingInfo({}).then((res) => {
      if (res.code == 200) {
        var bookingInfo = res.data.bookingInfo;

        var absId = bookingInfo.shopId;
        var spaId = bookingInfo.spaId;
        console.log(res.data);
        var latitude = wx.getStorageSync('latitude')
        var longitude = wx.getStorageSync('longitude')
        console.log(latitude + '===' + longitude)
        if (bookingInfo.gender == '男') {
          bookingInfo.gender = 1
        } else {
          bookingInfo.gender = 2
        }
        getshopinfo({
          absId: absId,
          latitude: latitude,
          longitude: longitude,
        }).then((res) => {
          if (res.code == 200) {
            var data = res.data
            bookingInfo.distance = Math.round(data.distance / 1000)
            bookingInfo.shopAddr = data.shopAddr
            t.setData({
              info: bookingInfo,
              shopTel: data.shopTel,
              latitude: data.latitude,
              longitude: data.longitude,
            });
          }
        })
      }
    })
  },

  // 评价提交
  confirmEvaluate(){
    let { starList } = this.data
    let score = {}
    starList.forEach((item)=>{
      score[item.key] = item.star
    })
    // 提交评价
    submitSpaBookingScore({...score}).then((res) => {
      if(res.code == 200){
        // 提交成功后关闭弹窗
        this.setData({
          showEvaluate: false,
          // 打开福利弹窗
          showWelfare: true,
        },()=>{
          // 开启接口轮询 查询是否升单
          this.pollingGetBookingInfo()
        })
      }else{
        showText(res.msg)
      }
    })
  },

  changeStar(e) {
    let { index ,ix} = e.currentTarget.dataset
    console.log(index,ix)
    let { starList } = this.data
    starList[index].star = ix + 1
    this.setData({
      starList,
    })
    
    console.log(starList)
  },
  // 确认福利
  confirmWelfare() {},
  confirmWelfareResult() {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },

  // 打开地图
  openLocation() {
    let { latitude, longitude } = this.data
    wx.openLocation({
      latitude,
      longitude,
      name: this.data.info.shop || '',
      complete: (com) => {
        console.log(com)
      },
    })
  },
  makePhoneCall() {
    wx.makePhoneCall({
      phoneNumber: '' + this.data.shopTel,
    })
  },
  openErcode() {
    let t = this
    let params = { qrCodeImg: t.data.qrCodeImg }
    this.setData({
      params
    });

    getBookingInfo({}).then((res) => {
      if (res.code == 200) {
        var bookingInfo = res.data.bookingInfo;
        this.handleBookResult(bookingInfo);

        if(bookingInfo.status == 2 && bookingInfo.scoreTime && !bookingInfo.upgradeTime){
          this.pollingGetBookingInfo()
        }
      }
    })

    //this.handleBookResult(this.data.info)
  },
  pollingGetBookingInfo(){
    clearInterval(this.data.pollingInterval)
    if(this.data.pollingInterval){
      this.setData({
        pollingInterval:null
      })
    }
    // 设置轮询间隔，例如每5秒轮询一次
    const pollInterval = 2000
    this.data.pollingInterval = setInterval(() => {
      getBookingInfo({}).then((res) => {
        if(res.code == 200){
          this.handleBookResult(res.data.bookingInfo);

        }
      })
    }, pollInterval)
  },

  // 处理结果
  handleBookResult(bookingInfo){
    if(bookingInfo.status == 1){
      this.setData({
        show: true,
      },()=>{
        // 开启接口轮询 查询是否核销
        this.pollingGetBookingInfo()
      })
    }
    // 如果status == 2（核销成功） && !scoreTime（未评分），弹出评价弹框，并关闭轮询
    if(bookingInfo.status == 2 && !bookingInfo.scoreTime){
      this.stopPolling()
      this.setData({
        show: false,
        showEvaluate: true,
      })
    }
    // 如果status == 2（核销成功） && scoreTime（已评分） && !upgradeTime (未升单)，弹出福利弹框，并关闭轮询
    if(bookingInfo.status == 2 && bookingInfo.scoreTime && !bookingInfo.upgradeTime){
      this.setData({
        showEvaluate: false,
        showWelfare: true,
      })
    }
    // 如果status == 2（核销成功） && scoreTime（已评分） && upgradeTime (已升单)，弹出福利结果弹框，并关闭轮询
    if(bookingInfo.status == 2 && bookingInfo.scoreTime && bookingInfo.upgradeTime){
      this.stopPolling()
      this.setData({
        showEvaluate: false,
        showWelfare: false,
        showWelfareResult: true,
      })
    }
  },

  // 停止轮询
  stopPolling: function () {
    if (this.data.pollingInterval) {
      clearInterval(this.data.pollingInterval)
    }
  },

  backHome() {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  closeProp10() {
    this.setData({
      show: false,
    })
    this.stopPolling()
  },
  closeDialog(e) {
    let { key } = e.currentTarget.dataset;
    console.log(key);
    this.stopPolling();
    this.setData({
      [key]: false,
    })
  },
  onShareAppMessage() {
    return {
      title: getApp().globalData.share_title,
      path: getApp().globalData.share_url,
      imageUrl: getApp().globalData.share_image,
    }
  }
})
